#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <signal.h>

#include <net/if.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include "cJSON/cJSON.h"

int main(int argc, char const *argv[])
{
    //获取指定服务器IP
    struct hostent *p;
    p = gethostbyname("wdexpress.market.alicloudapi.com");
    printf("服务器IP:%s\n", 
            inet_ntoa(*(struct in_addr*)((p->h_addr_list)[0])));

    //创建TCP连接
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    bzero(&addr, len);
    addr.sin_family = AF_INET;
    addr.sin_addr = *(struct in_addr*)((p->h_addr_list)[0]);
    addr.sin_port = htons(80);
    if(connect(sockfd, (struct sockaddr *)&addr, len) == 0)
        printf("连接成功\n");

    //按服务器规定发送请求报文
    char *http_request();
    char *s = http_request();
    write(sockfd, s, strlen(s));

    //接收、解析HTTP响应头部
    char *http_response = calloc(1, 1024);
    int n = 0;
    while(1)
    {
        read(sockfd, http_response + n, 1);
        n++;

        if(strstr(http_response, "\r\n\r\n"))
            break;
    }
    printf("HTTP响应头部:\n%s",http_response);

    char *json = calloc(1, 2048);  
    int nread = read(sockfd, json, 2048);
    char *pp = strtok(strchr(json, '\n')+1, "\r\n");
    printf("HTTP响应报体:(JSON)[%d字节]\n%s", nread, json);

    //解析cJSON
    cJSON *root = cJSON_Parse(pp);
    if(root == NULL)
        printf("json 解析失败\n");
    cJSON *Traces = cJSON_GetObjectItem(root, "Traces");
    if(Traces == NULL)
        printf("Traces 解析失败\n");

    for(int i=0; i<cJSON_GetArraySize(Traces); i++)
    {
        cJSON *item = cJSON_GetArrayItem(Traces, i);
        printf("时间：%s", cJSON_GetObjectItem(item, "AcceptTime")->valuestring);
        printf("站点：%s\n", cJSON_GetObjectItem(item, "AcceptStation")->valuestring);
    }

    return 0;
}

char *http_request()
{
    char *requestHead = "GET /gxali?n=780098068058&t=ZTO HTTP/1.1\r\n"
                        "Host: wdexpress.market.alicloudapi.com\r\n"
                        "Authorization: AppCode a83865167d05434f92a60aa5edb9498d\r\n\r\n";
    return requestHead;
}